﻿using MYQQX.SP;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MYQQX
{
    public delegate Card SendCardDelegate(List<Card> cards);
    public partial class MainForm : Form
    {
        public static SendCardDelegate NextSend = null;
        public static event SendCardDelegate ContinueSend;

        private CardGroup MyGroup = new CardGroup();
        private CardGroup AiGroup = new CardGroup();
        private GameInfo _GameInfo;
        public MainForm(GameInfo gameInfo,List<ISp> useList,List<ISp> aiList)
        {
            _GameInfo = gameInfo;
            InitializeComponent();

            clAI.ShowCard = false;
            clMy.ShowCardAct = this.ChoseCard;

            MyGroup.ShowList = clMy;
            MyGroup.spList = useList;
            MyGroup.OtherGroup = AiGroup;

            AiGroup.ShowList = clAI;
            AiGroup.spList = aiList;
            AiGroup.AI = true;
            AiGroup.OtherGroup = MyGroup;

            StartGame();
        }

        private void ChoseCard(Card obj)
        {
            clDesk.NeedSeason = obj.JiJie;
        }

        private void StartGame()
        {
            // 初始化卡池
            InitCard();

            // 初始化稀有卡
        }

        private List<Card> AllCards = new List<Card>();

        /// <summary>
        /// 初始化卡排堆
        /// </summary>
        private void InitCard()
        {
            this.AllCards = CardConfig.Instance.GetCardList(_GameInfo.H1, _GameInfo.H2, _GameInfo.H3);

            // 1. 发10张卡给玩家
            clMy.AddCard(GetCard(10));

            // 2. 发10张给AI
            clAI.AddCard(GetCard(10));

            // 3. 发10张到公共池
            clDesk.AddCard(GetCard(10));
        }

        /// <summary>
        /// 公共牌堆补到10张
        /// </summary>
        private void ResetCard()
        {
            clDesk.AddCard(GetCard(10 - clDesk.cardList.Count));
        }

        private void btnMyList_Click(object sender, EventArgs e)
        {
            ShowForm frm = new ShowForm(MyGroup);
            frm.StartPosition = FormStartPosition.CenterParent;
            frm.ShowDialog();
        }

        private List<Card> GetCard(int number)
        {
            // 下回合出现卡牌的指定逻辑（一次性）
            if (number == 1 && NextSend != null)
            {
                var nc = NextSend.Invoke(AllCards);
                NextSend = null;
                if (nc != null)
                {
                    AllCards.Remove(nc);
                    return new List<Card> { nc };
                }
            }

            // 持续性质的排牌逻辑
            if (number == 1)
            {
                var nc = ContinueSend?.Invoke(AllCards);
                if (nc != null)
                {
                    AllCards.Remove(nc);
                    return new List<Card> { nc };
                }
            }

            var list = AllCards.Take(number).ToList();
            AllCards.RemoveRange(0, number);
            return list;
        }

        private bool CanGroup;
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (clMy.ChoseCard != null && clDesk.ChoseCard != null
                && clMy.ChoseCard.JiJie == clDesk.ChoseCard.JiJie)
            {
                var nGps = MyGroup.AddCard(false, clMy.ChoseCard, clDesk.ChoseCard);
                clMy.UseChose();
                clDesk.UseChose();
                foreach (var gp in nGps)
                {
                    ScoreForm.Show("玩家", gp);
                }

                btnMyList.Text = $"组合卡牌\r\n{MyGroup.CurrentScore}分";

                clDesk.NeedSeason = CardSeason.Null;

                ResetCard();

                AIGo();
            }
            else if (clMy.ChoseCard != null && !CanGroup)
            {
                // 换牌：选中牌到桌面，然后补充一张牌，继续出
                
                clDesk.AddCard(new List<Card>() { clMy.ChoseCard.Clone()});
                clMy.UseChose();
                clMy.AddCard(GetCard(1));

                PlayerGo();
            }
        }

        private void PlayerGo()
        {
            if (clMy.cardList.Count <= 0 && clAI.cardList.Count <= 0)
            {
                ShowEnd();
                return;
            }

            CanGroup = clMy.cardList.Select(t => t.JiJie)
                .Intersect(clDesk.cardList.Select(t => t.JiJie))
                .Any() ;
        }

        private void AIGo()
        {
            if (clMy.cardList.Count <= 0 && clAI.cardList.Count <= 0)
            {
                ShowEnd();
                return;
            }
            AI ai = new AI()
            {
                HaveList = AiGroup.cardList,
                DeskList = clDesk.cardList,
                HandList = clAI.cardList
            };

            ai.Go();

            if (ai.DeskChose != null)
            {
                clAI.setChose(ai.HandChose);
                clDesk.setChose(ai.DeskChose);

                var nGps = AiGroup.AddCard(false, clAI.ChoseCard, clDesk.ChoseCard);
                clAI.UseChose();
                clDesk.UseChose();
                foreach (var gp in nGps)
                {
                    ScoreForm.Show("AI", gp);
                }

                btnAIList.Text = $"组合卡牌\r\n{AiGroup.CurrentScore}分";

                clDesk.NeedSeason = CardSeason.Null;

                ResetCard();

                PlayerGo();
            }
            else
            {
                clAI.setChose(ai.HandChose);
                clDesk.AddCard(new List<Card>() { ai.HandChose.Clone() });
                clAI.UseChose();
                clAI.AddCard(GetCard(1));

                AIGo();
            }
        }

        private void ShowEnd()
        {
            if (MyGroup.CurrentScore > AiGroup.CurrentScore)
            {
                MessageBox.Show("恭喜你，胜利！", "胜利", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("请再接再厉！", "失败", buttons: MessageBoxButtons.OK, icon: MessageBoxIcon.Information);
            }
        }

        private void btnAIList_Click(object sender, EventArgs e)
        {
            ShowForm frm = new ShowForm(AiGroup);
            frm.StartPosition = FormStartPosition.CenterParent;
            frm.ShowDialog();
        }

        private void btnMyXy_Click(object sender, EventArgs e)
        {
            ShowXyForm frm = new ShowXyForm(MyGroup);
            frm.ShowDialog();
        }

        private void btnAIXY_Click(object sender, EventArgs e)
        {
            ShowXyForm frm = new ShowXyForm(AiGroup);
            frm.ShowDialog();
        }
    }
}
